import { Button, Card, Modal, Tag, message } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { isEmpty, isNil } from "ramda";
import { useEffect, useMemo, useState } from "react";

import { SvgIcon } from "@/components/icon";

import MenuModal, { type MenuModalProps } from "./EditForm";

import menuService from "@/api/services/system/menuService";
import DictionaryTag from "@/components/grid/TableDictTag";
import { TableToolbar } from "@/components/grid/TableToolbar";
import { DeleteOutlined, EditOutlined, MinusOutlined, PlusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import type { Menu } from "#/entity";
import { BasicStatus, MenuType } from "#/enum";
import ReactIcon from "@/components/icon/ReactIcon";

const defaultMenuValue: Menu = {
	id: "",
	parentId: "",
	name: "",
	label: "",
	route: "",
	component: "",
	icon: "",
	hidden: "0",
	status: BasicStatus.ENABLE,
	type: MenuType.CATALOGUE,
};

export default function MenuPage() {
	const [menuModalProps, setMenuModalProps] = useState<MenuModalProps>({
		formValue: { ...defaultMenuValue },
		title: "新增",
		show: false,
		onOk: () => {
			setMenuModalProps((prev) => ({ ...prev, show: false }));
			getMenus();
		},
		onCancel: () => {
			setMenuModalProps((prev) => ({ ...prev, show: false }));
		},
	});
	const [loading, setLoading] = useState(false);
	const [menus, setMenus] = useState<Menu[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");

	// 表格列
	const columns: ColumnsType<Menu> = [
		{
			title: "名称",
			dataIndex: "name",
			key: "name",
			width: 300,
		},
		{
			title: "类型",
			dataIndex: "type",
			key: "type",
			width: 60,
			render: (_, record) => <DictionaryTag dictCode="menu_type" value={record.type} />,
		},
		{
			title: "图标",
			dataIndex: "icon",
			key: "icon",
			width: 60,
			render: (icon: string) => {
				if (isEmpty(icon) || isNil(icon)) return "";

				if (icon.startsWith("ic")) {
					return <SvgIcon icon={icon} size={18} className="ant-menu-item-icon" />;
				}
				return <ReactIcon name={icon} size={18} className="ant-menu-item-icon" />;
			},
		},
		{
			title: "组件路径",
			dataIndex: "component",
			key: "component",
		},
		{
			title: "状态",
			dataIndex: "status",
			key: "status",
			align: "center",
			width: 120,
			render: (status) => (
				<Tag color={status === BasicStatus.DISABLE ? "error" : "success"}>
					{status === BasicStatus.DISABLE ? "失效" : "有效"}
				</Tag>
			),
		},
		{ title: "排序", dataIndex: "sn", key: "sn", width: 60 },
		{
			title: "操作",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<div className="flex w-full justify-end text-gray">
					{record?.type !== MenuType.BUTTON && (
						<Button type="text" onClick={() => onCreate(record.id)} icon={<PlusCircleOutlined />} />
					)}
					<Button type="text" onClick={() => onEdit(record)} icon={<EditOutlined />} />

					<Button type="text" onClick={() => handleDelete(record)} icon={<DeleteOutlined />} />
				</div>
			),
		},
	];

	// 状态管理
	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => (col.key ? String(col.key) : "")),
	);

	// 处理过滤后的列配置
	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	const filteredColumns = useMemo(() => {
		return [
			// 显示选中的列
			...columns.filter(
				(col) => selectedValues.includes(String(col.key)) || col.key === "operation", // 始终包含操作列
			),
		].sort((a, b) => {
			// 保持原始顺序
			const originalIndex = columns.findIndex((c) => c.key === a.key);
			const targetIndex = columns.findIndex((c) => c.key === b.key);
			return originalIndex - targetIndex;
		});
	}, [selectedValues]);

	useEffect(() => {
		getMenus();
	}, []);

	const getMenus = async () => {
		try {
			setLoading(true);
			const res = await menuService.queryAll();
			setMenus(res);
		} catch (error) {
			console.error("获取菜单列表失败:", error);
			message.error("获取菜单列表失败:");
		} finally {
			setLoading(false);
		}
	};

	const onCreate = (parentId?: string) => {
		setMenuModalProps((prev) => ({
			...prev,
			show: true,
			...defaultMenuValue,
			title: "新增菜单",
			formValue: { ...defaultMenuValue, parentId: parentId ?? "" },
		}));
	};

	const onEdit = (formValue: Menu) => {
		if (formValue.parentId && formValue.parentId === "0") {
			formValue.parentId = undefined;
		}
		console.log("打开编辑页面", formValue);
		setMenuModalProps((prev) => ({
			...prev,
			show: true,
			title: "编辑菜单",
			formValue,
		}));
	};

	const handleDelete = (record: Menu) => {
		Modal.confirm({
			title: "确认删除",
			content: "确定要删除该菜单及子菜单吗？删除后将无法恢复。",
			onOk: async () => {
				try {
					setLoading(true);
					await menuService.deleteById(record.id);
					message.success("删除成功");
					getMenus();
				} catch (error) {
					message.error("删除失败");
				} finally {
					setLoading(false);
				}
			},
		});
	};

	return (
		<Card>
			<div className="flex justify-between mb-4">
				{/* 操作按钮 */}
				<div className="flex gap-2">
					<Button type="primary" onClick={() => onCreate()}>
						新增
					</Button>
				</div>
				<TableToolbar
					onRefresh={() => getMenus()}
					onSizeChange={setTableSize}
					columns={columns}
					selectedValues={selectedValues}
					onColumnChange={setSelectedValues}
				/>
			</div>
			<Table
				rowKey="id"
				size={tableSize}
				loading={loading}
				scroll={{ x: "max-content" }}
				pagination={false}
				columns={filteredColumns}
				dataSource={menus}
				expandable={{
					expandIcon: ({ expanded, onExpand, record }) => {
						if (!record.children || record.children.length === 0) {
							return null; // 如果没有子节点，不显示展开图标
						}
						return (
							<span onClick={(e) => onExpand(record, e)} className="mr-2">
								{expanded ? <MinusOutlined /> : <PlusOutlined />}
							</span>
						);
					},
				}}
			/>

			<MenuModal {...menuModalProps} />
		</Card>
	);
}
